package com.zlm.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlm.constants.SysConstants;
import com.zlm.domain.entity.Article;
import com.zlm.service.ArticleService;
import com.zlm.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zlm
 * @date 2024/12/11
 * 项目启动时加载文章浏览量到redis
 */
@Component
public class ViewCountCommandLineRunner implements CommandLineRunner {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, "0");
        List<Article> list = articleService.list();

        Map<String, Integer> viewCount = list.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> article.getViewCount().intValue()));
        redisCache.setCacheMap(SysConstants.ARTICLE_VIEW_COUNT, viewCount);
    }
}
